import { useState, useRef, useCallback } from 'react';
import Webcam from 'react-webcam';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation } from 'swiper/modules';
import type { Swiper as SwiperType } from 'swiper';
import html2canvas from 'html2canvas';
import { Button, message } from 'antd';
import QRCode from 'qrcode.react';
import axios from 'axios';
import 'swiper/css';
import 'swiper/css/navigation';

// 模板图片列表
const templates = [
  '/templates/template1.png',
  '/templates/template2.png',
  '/templates/template3.png',
];

export default function Home() {
  const [currentTemplate, setCurrentTemplate] = useState(0);
  const [showQRCode, setShowQRCode] = useState(false);
  const [orderId, setOrderId] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const webcamRef = useRef<Webcam>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  const handleCapture = useCallback(async () => {
    if (!containerRef.current) return;

    try {
      setIsLoading(true);
      const canvas = await html2canvas(containerRef.current, {
        useCORS: true,
        allowTaint: true,
      });
      const imageData = canvas.toDataURL('image/png');

      // 调用后端API创建订单
      const response = await axios.post('/api/create-order', {
        imageData,
        templateId: currentTemplate,
      });

      setOrderId(response.data.orderId);
      setShowQRCode(true);
    } catch (error) {
      console.error('Error capturing image:', error);
      message.error('拍照失败，请重试');
    } finally {
      setIsLoading(false);
    }
  }, [currentTemplate]);

  const handleTemplateChange = (swiper: SwiperType) => {
    setCurrentTemplate(swiper.activeIndex);
  };

  return (
    <div className="relative w-full h-screen bg-black">
      <div ref={containerRef} className="relative w-full h-full">
        <Webcam
          ref={webcamRef}
          audio={false}
          className="w-full h-full object-cover"
          screenshotFormat="image/jpeg"
          videoConstraints={{
            facingMode: 'user',
            width: { ideal: 1920 },
            height: { ideal: 1080 },
          }}
        />
        <div className="absolute top-0 left-0 w-full h-full">
          <Swiper
            modules={[Navigation]}
            navigation
            onSlideChange={handleTemplateChange}
            className="w-full h-full"
          >
            {templates.map((template, index) => (
              <SwiperSlide key={index}>
                <img
                  src={template}
                  alt={`Template ${index + 1}`}
                  className="w-full h-full object-contain"
                  crossOrigin="anonymous"
                />
              </SwiperSlide>
            ))}
          </Swiper>
        </div>
      </div>

      {!showQRCode ? (
        <Button
          type="primary"
          size="large"
          className="absolute bottom-8 left-1/2 transform -translate-x-1/2"
          onClick={handleCapture}
          loading={isLoading}
        >
          拍照
        </Button>
      ) : (
        <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white p-4 rounded-lg">
          <QRCode value={`/payment/${orderId}`} size={200} />
          <p className="text-center mt-4">请扫码支付</p>
        </div>
      )}
    </div>
  );
} 